<template>
  <el-dialog
    @close="cjjsdCancel('cjjsdRuleForm')"
    :close-on-click-modal="false"
    title="出具结算单"
    :visible.sync="cjjsdVisible"
    width="950px"
  >
    <div class="scroll-view">
      <el-form
        :model="cjjsdRuleForm"
        :rules="cjjsdRules"
        ref="cjjsdRuleForm"
        label-position="left"
        inline
      >
        <el-form-item label="合同金额" prop="contract_price">
          <el-input
            disabled
            class="input-box"
            clearable
            v-model="cjjsdRuleForm.contract_price"
            v-input-limit="2"
          ></el-input>
        </el-form-item>
        <el-form-item label="结算税金" prop="settlement_taxes">
          <el-input
            @input="inputFunc"
            class="input-box"
            clearable
            v-model="cjjsdRuleForm.settlement_taxes"
            v-input-limit="2"
          ></el-input>
        </el-form-item>
        <el-form-item label="增减项总金额" prop="changes_amount">
          <el-input
            disabled
            class="input-box"
            clearable
            v-model="cjjsdRuleForm.changes_amount"
            v-input-limit="2"
          ></el-input>
        </el-form-item>

        <el-form-item label="应结算金额" prop="settlement_amount">
          <el-input
            disabled
            class="input-box"
            clearable
            v-model="cjjsdRuleForm.settlement_amount"
            v-input-limit="2"
          ></el-input>
        </el-form-item>
        <el-form-item label="管理成本(结算)" prop="management_costs">
          <el-input
            @input="inputFunc"
            class="input-box"
            clearable
            v-model="cjjsdRuleForm.management_costs"
            v-input-limit="2"
          ></el-input>
        </el-form-item>
        <el-form-item label="现场采购成本(结算)" prop="procurement_cost">
          <el-input
            disabled
            class="input-box"
            clearable
            v-model="cjjsdRuleForm.procurement_cost"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="公司集采成本(结算)"
          prop="centralized_procurement_cost"
        >
          <el-input
            disabled
            class="input-box"
            clearable
            v-model="cjjsdRuleForm.centralized_procurement_cost"
          ></el-input>
        </el-form-item>
        <el-form-item label="利润金额" prop="profit_amount">
          <el-input
            disabled
            class="input-box"
            clearable
            v-model="cjjsdRuleForm.profit_amount"
          ></el-input>
        </el-form-item>
        <el-form-item label="已付款金额" prop="paid_amount">
          <el-input
            disabled
            class="input-box"
            clearable
            v-model="cjjsdRuleForm.paid_amount"
            v-input-limit="2"
          ></el-input>
        </el-form-item>
        <el-form-item label="待付款金额" prop="unpaid_amount">
          <el-input
            disabled
            class="input-box"
            clearable
            v-model="cjjsdRuleForm.unpaid_amount"
            v-input-limit="2"
          ></el-input>
        </el-form-item>
        <el-form-item label="成本金额(结算)" prop="settlement_cost_amount">
          <el-input
            disabled
            class="input-box"
            clearable
            v-model="cjjsdRuleForm.settlement_cost_amount"
            v-input-limit="2"
          ></el-input>
        </el-form-item>
        <el-form-item label="利润率(结算)" prop="settlement_profit_margin">
          <el-input
            disabled
            class="input-box"
            clearable
            v-model="cjjsdRuleForm.settlement_profit_margin"
            v-input-limit="2"
          >
            <span slot="suffix">%</span>
          </el-input>
        </el-form-item>
        <el-form-item
          label="结算文件 (.ppt,.xls,.pdf,.doc,.docx,.xlsx)"
          prop="settlement_file"
        >
          <el-input
            style="position: absolute; z-index: 0; top: -999999px"
            v-model="cjjsdRuleForm.settlement_file.length"
          ></el-input>
          <el-upload
            :on-change="
              (file, fileList) => {
                cjjsdChangeFile(file, fileList, 'settlement_file');
              }
            "
            :on-remove="
              (file, fileList) => {
                cjjsdFileRemove(file, fileList, 'settlement_file');
              }
            "
            :auto-upload="false"
            accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx"
            :file-list="cjjsdRuleForm.settlement_file"
            action="#"
            ><el-button size="small" icon="el-icon-plus">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="工程量清单 (.ppt,.xls,.pdf,.doc,.docx,.xlsx)"
          prop="inventory_file"
        >
          <el-input
            style="position: absolute; z-index: 0; top: -999999px"
            v-model="cjjsdRuleForm.inventory_file.length"
          ></el-input>
          <el-upload
            :on-change="
              (file, fileList) => {
                cjjsdChangeFile(file, fileList, 'inventory_file');
              }
            "
            :on-remove="
              (file, fileList) => {
                cjjsdFileRemove(file, fileList, 'inventory_file');
              }
            "
            :auto-upload="false"
            accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx"
            :file-list="cjjsdRuleForm.inventory_file"
            action="#"
            ><el-button size="small" icon="el-icon-plus">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item
          label="利润单文件 (.ppt,.xls,.pdf,.doc,.docx,.xlsx)"
          prop="profit_statement_file"
        >
          <el-input
            style="position: absolute; z-index: 0; top: -999999px"
            v-model="cjjsdRuleForm.profit_statement_file.length"
          ></el-input>
          <el-upload
            :on-change="
              (file, fileList) => {
                cjjsdChangeFile(file, fileList, 'profit_statement_file');
              }
            "
            :on-remove="
              (file, fileList) => {
                cjjsdFileRemove(file, fileList, 'profit_statement_file');
              }
            "
            :auto-upload="false"
            accept=".ppt,.xls,.pdf,.doc,.docx,.xlsx"
            :file-list="cjjsdRuleForm.profit_statement_file"
            action="#"
            ><el-button size="small" icon="el-icon-plus">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            :rows="4"
            class="input-box"
            v-model="cjjsdRuleForm.remark"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer">
      <el-button
        type="primary"
        clearable
        @click="cjjsdSubmit('cjjsdRuleForm')"
        :disabled="diaLoading"
        :loading="diaLoading"
        >提交</el-button
      >
      <el-button @click="cjjsdCancel('cjjsdRuleForm')">关闭</el-button>
    </span>
  </el-dialog>
</template>
<script>
import projectApi from "@/api/projectApi";
import companyApi from "@/api/companyApi";
import adminApi from "@/api/adminApi";
import { getUserInfo } from "@/utils/auth";
import foremanApi from "@/api/foremanApi";
import * as math from "mathjs";

export default {
  name: "",
  props: {
    addDialogVisible: {
      type: Boolean,
      default: false,
      required: false,
    },
    project_id: {
      required: false,
    },
    detailData: {
      required: false,
    },
    signing_company_data: {
      required: false,
    },
  },
  data() {
    var file = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error("请上传文件"));
      } else {
        callback();
      }
    };
    return {
      diaLoading: false,
      cjjsdVisible: false,
      cjjsdRuleForm: {
        remark: "",
        contract_price: "",
        changes_amount: "",
        settlement_amount: "",
        procurement_cost: "",
        centralized_procurement_cost: "",
        management_costs: "",
        profit_amount: "",
        paid_amount: "",
        unpaid_amount: "",
        settlement_file: [],
        inventory_file: [],
        profit_statement_file: [],
        settlement_taxes: "",
        settlement_profit_margin: "",
        settlement_cost_amount: "",
      },
      cjjsdRules: {
        contract_price: [
          { required: true, message: "请输入合同金额", trigger: "change" },
        ],
        changes_amount: [
          { required: true, message: "请输入增减项总金额", trigger: "change" },
        ],
        settlement_amount: [
          { required: true, message: "请输入应结算金额", trigger: "change" },
        ],
        procurement_cost: [
          { required: true, message: "请输入现场采购成本", trigger: "change" },
        ],
        centralized_procurement_cost: [
          { required: true, message: "请输入公司集采成本", trigger: "change" },
        ],
        management_costs: [
          { required: true, message: "请输入管理成本", trigger: "change" },
        ],
        profit_amount: [
          { required: true, message: "请输入利润金额", trigger: "change" },
        ],
        paid_amount: [
          { required: true, message: "请输入已支付金额", trigger: "change" },
        ],
        unpaid_amount: [
          { required: true, message: "请输入待支付金额", trigger: "change" },
        ],
        settlement_taxes: [
          { required: true, message: "请输入结算税金", trigger: "change" },
        ],
        settlement_profit_margin: [
          { required: true, message: "请输入结算利润率", trigger: "change" },
        ],
        settlement_cost_amount: [
          { required: true, message: "请输入成本金额", trigger: "change" },
        ],
        settlement_file: {
          required: true,
          validator: file,
          trigger: "change",
        },
        inventory_file: {
          required: true,
          validator: file,
          trigger: "change",
        },
        profit_statement_file: {
          required: true,
          validator: file,
          trigger: "change",
        },
      },
      profit_amount: 0,
    };
  },
  watch: {
    addDialogVisible(val1, val2) {
      if (this.addDialogVisible) {
        let detailData = this.detailData;
        console.log(detailData, "项目数据");
        let signing_company_data = this.signing_company_data;
        console.log(signing_company_data, "合同数据");
        let cjjsdRuleForm = this.cjjsdRuleForm;

        let contract_price = signing_company_data.contract_price; //合同金额
        cjjsdRuleForm.contract_price = contract_price;
        console.log(contract_price, "合同金额");
        let changes_amount = 0; //增减项总金额
        changes_amount = math.format(
          math.subtract(
            math.bignumber(detailData.change_add),
            math.bignumber(detailData.change_subtract)
          )
        );
        if (changes_amount != 0) {
          changes_amount = ((changes_amount * 100) / 100).toFixed(2);
        } else {
          changes_amount = (changes_amount * 100) / 100;
        }
        cjjsdRuleForm.changes_amount = changes_amount;
        console.log(changes_amount, "增减项总金额");
        let settlement_amount = 0; //应结算金额
        settlement_amount = math.format(
          math.add(
            math.bignumber(changes_amount),
            math.bignumber(contract_price)
          )
        );
        settlement_amount = ((settlement_amount * 100) / 100).toFixed(2);
        cjjsdRuleForm.settlement_amount = settlement_amount;
        console.log(settlement_amount, "应结算金额");
        let procurement_cost = 0; //现场采购成本
        let procurementVal1 = math.format(
          math.add(
            math.bignumber(detailData.procurement_cost), //造价单现场采购
            math.bignumber(detailData.procurement_cost_add) //增项现场采购
          )
        );
        procurementVal1 = ((procurementVal1 * 100) / 100).toFixed(2);
        procurement_cost = math.format(
          math.subtract(
            math.bignumber(procurementVal1),
            math.bignumber(detailData.procurement_cost_subtract) //减项现场采购
          )
        );
        procurement_cost = ((procurement_cost * 100) / 100).toFixed(2);
        cjjsdRuleForm.procurement_cost = procurement_cost;
        console.log(procurement_cost, "结算现场采购成本");
        let centralized_procurement_cost = 0; //公司采购成本
        let centralized_procurement_costVal1 = math.format(
          math.add(
            math.bignumber(detailData.centralized_procurement_cost), //造价单公司采购
            math.bignumber(detailData.centralized_procurement_cost_add) //增项公司采购
          )
        );
        centralized_procurement_costVal1 = (
          (centralized_procurement_costVal1 * 100) /
          100
        ).toFixed(2);
        centralized_procurement_cost = math.format(
          math.subtract(
            math.bignumber(centralized_procurement_costVal1),
            math.bignumber(detailData.centralized_procurement_cost_subtract) //减项公司采购
          )
        );
        cjjsdRuleForm.centralized_procurement_cost =
          centralized_procurement_cost;
        console.log(centralized_procurement_cost, "结算公司采购成本");
        let settlement_cost_amount = 0; //成本金额
        settlement_cost_amount = math.format(
          math.add(
            math.bignumber(procurement_cost),
            math.bignumber(centralized_procurement_cost)
          )
        );
        settlement_cost_amount = ((settlement_cost_amount * 100) / 100).toFixed(
          2
        );
        cjjsdRuleForm.settlement_cost_amount = settlement_cost_amount;
        console.log(settlement_cost_amount, "成本金额（初步计算）");
        let paid_amount = 0; //已支付金额
        paid_amount = math.format(
          math.add(
            math.bignumber(detailData.advance_charge),//预付款100000
            math.bignumber(detailData.survey_fees),//勘场费用20
            math.bignumber(detailData.progress_payment),//进度款500
            math.bignumber(detailData.change_add)//增减项总金额
          )
        );
        paid_amount = ((paid_amount * 100) / 100).toFixed(2);
        cjjsdRuleForm.paid_amount = paid_amount;
        console.log(paid_amount, "已支付金额");
        let unpaid_amount = 0; //待支付金额
        unpaid_amount = math.format(
          math.subtract(
            math.bignumber(settlement_amount),
            math.bignumber(paid_amount)
          )
        );
        unpaid_amount = ((unpaid_amount * 100) / 100).toFixed(2);
        cjjsdRuleForm.unpaid_amount = unpaid_amount;
        console.log(unpaid_amount, "待支付");
        let profit_amount = 0; //利润金额
        profit_amount = math.format(
          math.subtract(
            math.bignumber(settlement_amount),
            math.bignumber(settlement_cost_amount)
          )
        );
        profit_amount = ((profit_amount * 100) / 100).toFixed(2);
        cjjsdRuleForm.profit_amount = profit_amount;
        console.log(profit_amount, "利润金额（初步计算）");
        let settlement_profit_margin = 0; //利润率
        let val1 = math.format(
          math.subtract(
            math.bignumber(settlement_amount),
            math.bignumber(settlement_cost_amount)
          )
        );
        val1 = ((val1 * 100) / 100).toFixed(2);
        settlement_profit_margin = math.format(
          math.divide(
            math.bignumber(val1),
            math.bignumber(settlement_cost_amount)
          )
        );
        settlement_profit_margin = (settlement_profit_margin * 100).toFixed(2);
        cjjsdRuleForm.settlement_profit_margin = settlement_profit_margin;
        console.log(settlement_profit_margin, "利润率（初步计算）");

        this.cjjsdRuleForm = cjjsdRuleForm;
      }
      this.cjjsdVisible = this.addDialogVisible;
    },
  },
  computed: {},
  mounted() {},
  methods: {
    // 出具结算单
    cjjsdCancel(formName) {
      this.cjjsdRuleForm = {
        remark: "",
        contract_price: "",
        changes_amount: "",
        settlement_amount: "",
        procurement_cost: "",
        centralized_procurement_cost: "",
        management_costs: "",
        profit_amount: "",
        paid_amount: "",
        unpaid_amount: "",
        settlement_file: [],
        inventory_file: [],
        profit_statement_file: [],
        settlement_taxes: "",
        settlement_profit_margin: "",
        settlement_cost_amount: "",
      };
      this.$nextTick(() => {
        this.$refs[formName].clearValidate();
        this.$emit("onClose", true);
      });
    },
    cjjsdSubmit(formName) {
      let cjjsdRuleForm = this.cjjsdRuleForm;
      console.log(cjjsdRuleForm, "出具结算单参数");
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.diaLoading = true;
          let formdata = new FormData();
          formdata.append(
            "data",
            JSON.stringify({
              remark: cjjsdRuleForm.remark,
              contract_price: cjjsdRuleForm.contract_price,
              changes_amount: cjjsdRuleForm.changes_amount,
              settlement_amount: cjjsdRuleForm.settlement_amount,
              procurement_cost: cjjsdRuleForm.procurement_cost,
              centralized_procurement_cost:
                cjjsdRuleForm.centralized_procurement_cost,
              management_costs: cjjsdRuleForm.management_costs,
              profit_amount: cjjsdRuleForm.profit_amount,
              paid_amount: cjjsdRuleForm.paid_amount,
              unpaid_amount: cjjsdRuleForm.unpaid_amount,
              settlement_taxes: cjjsdRuleForm.settlement_taxes,
              settlement_cost_amount: cjjsdRuleForm.settlement_cost_amount,
              settlement_profit_margin: cjjsdRuleForm.settlement_profit_margin,
              project_id: this.project_id,
            })
          );
          cjjsdRuleForm.settlement_file.forEach((item) => {
            formdata.append("settlement_file[]", item.raw);
          });
          cjjsdRuleForm.inventory_file.forEach((item) => {
            formdata.append("inventory_file[]", item.raw);
          });
          cjjsdRuleForm.profit_statement_file.forEach((item) => {
            formdata.append("profit_statement_file[]", item.raw);
          });
          projectApi
            .issueSettlementStatement(formdata)
            .then((res) => {
              console.log(res, "出具结算单");
              this.diaLoading = false;
              if (res.code == 200) {
                this.$emit("onSuccess", true);
              }
              this.$message({
                type: res.code == 200 ? "success" : "warning",
                message: res.code == 200 ? "处理成功" : res.message,
              });
            })
            .catch((err) => {
              this.diaLoading = false;
              this.$message({
                type: "warning",
                message: err.message,
              });
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 管理成本
    inputFunc() {
      let detailData = this.detailData;
      let cjjsdRuleForm = this.cjjsdRuleForm;
      let settlement_taxes = cjjsdRuleForm.settlement_taxes || 0; //税金
      let management_costs = cjjsdRuleForm.management_costs || 0; //管理成本
      let centralized_procurement_cost =
        cjjsdRuleForm.centralized_procurement_cost; //公司采购
      let procurement_cost = cjjsdRuleForm.procurement_cost; //现场采购
      let settlement_amount = cjjsdRuleForm.settlement_amount; //应结算金额
      let settlement_cost_amount = 0; //成本金额
      let profit_amount = 0; //利润金额
      let settlement_profit_margin = 0; //利润率
      settlement_cost_amount = math.format(
        math.add(
          math.bignumber(procurement_cost),
          math.bignumber(centralized_procurement_cost),
          math.bignumber(settlement_taxes),
          math.bignumber(management_costs)
        )
      );
      settlement_cost_amount = ((settlement_cost_amount * 100) / 100).toFixed(
        2
      );
      cjjsdRuleForm.settlement_cost_amount = settlement_cost_amount;
      console.log(settlement_cost_amount, "成本金额");
      profit_amount = math.format(
        math.subtract(
          math.bignumber(settlement_amount),
          math.bignumber(settlement_cost_amount)
        )
      );
      profit_amount = ((profit_amount * 100) / 100).toFixed(2);
      cjjsdRuleForm.profit_amount = profit_amount;
      console.log(profit_amount, "利润金额");

      let val1 = math.format(
        math.subtract(
          math.bignumber(settlement_amount),
          math.bignumber(settlement_cost_amount)
        )
      );
      val1 = ((val1 * 100) / 100).toFixed(2);
      settlement_profit_margin = math.format(
        math.divide(
          math.bignumber(val1),
          math.bignumber(settlement_cost_amount)
        )
      );
      settlement_profit_margin = (settlement_profit_margin * 100).toFixed(2);
      cjjsdRuleForm.settlement_profit_margin = settlement_profit_margin;
      console.log(settlement_profit_margin, "利润率");

      this.cjjsdRuleForm = cjjsdRuleForm;
    },
    //
    cjjsdChangeFile(file, list, type) {
      console.log(file, list, type);
      let cjjsdRuleForm = this.cjjsdRuleForm;
      cjjsdRuleForm[type] = [file];
      this.cjjsdRuleForm;
    },
    cjjsdFileRemove(file, list, type) {
      console.log(file, list, type);
      let cjjsdRuleForm = this.cjjsdRuleForm;
      cjjsdRuleForm[type] = list;
      this.cjjsdRuleForm;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>